/* echo_tcp_cl.c

   A server that send datatream。

   See also echo_tcp_sv.c.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> /*for bzero*/
#include <unistd.h>

#include "echo_tcp.h"

static void errExit(char *msg) {
  perror(msg);
  exit(EXIT_FAILURE);
}

int main(int argc, char **argv) {
  int sockfd, nwrite, nmsg;
  struct sockaddr_in servaddr;

  if (argc < 3) {
    fprintf(stderr, "usage: tcpclient <IPaddress> msg");
    exit(EXIT_FAILURE);
  }

  sockfd = socket(AF_INET, SOCK_STREAM, 0);

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(PORT_NUM);
  inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);

  int connect_rt =
      connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
  if (connect_rt < 0) {
    errExit("connect");
  }

  for (int j = 2; j < argc; j++) {
    nmsg = strlen(argv[j]);
    nwrite = send(sockfd, &nmsg, sizeof(int), 0);
    if (nwrite != sizeof(int)) {
      errExit("send");
    }
    nwrite = send(sockfd, argv[j], nmsg, 0);
    fprintf(stdout, "send into buffer %d \n", nwrite);
  }

  close(sockfd);

  return 0;
}
